//
//  MainLiveInPutTollBarView.m
//  v8090Video
//
//  Created by 陈建 on 2018/9/6.
//  Copyright © 2018年 BlueWind. All rights reserved.
//

#import "MainLiveInPutTollBarView.h"

//输入框高度
#define kInputHeight 34
//按钮高
#define kButtonH 30
//按钮宽
#define kButtonW 65




#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]

@interface MainLiveInPutTollBarView () <UITextViewDelegate>{
    CGFloat _chazhi;
}

@property (nonatomic, strong) UIView *textInputBackView;

/***文本输入框最高高度***/
@property (nonatomic, assign)NSInteger textInputMaxHeight;

/***文本输入框高度***/
@property (nonatomic, assign)CGFloat textInputHeight;

/***键盘高度***/
@property (nonatomic, assign)CGFloat keyboardHeight;

/***当前键盘是否可见*/
@property (nonatomic,assign)BOOL keyboardIsVisiable;
// 发送按钮
@property (nonatomic, strong) UIButton *sendBtn;


@property (nonatomic,assign) CGFloat origin_y;
@property (nonatomic,assign) CGFloat currentPut_Y;
@end

@implementation MainLiveInPutTollBarView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor orangeColor];
        self.origin_y = frame.origin.y;
        _chazhi = self.height - kInputHeight;
        [self initView];
        
        [self setupSubviews];
        
        [self addEventListening];
    }
    return self;
}

-(void)initView
{
    self.backgroundColor = [UIColor whiteColor];
    if (!self.textViewMaxLine || self.textViewMaxLine == 0) {
        self.textViewMaxLine = 4;
    }
}
- (void)setTextViewMaxLine:(NSInteger)textViewMaxLine
{
    _textViewMaxLine = textViewMaxLine;
    _textInputMaxHeight = ceil(self.textInput.font.lineHeight * (textViewMaxLine - 1) +
                               self.textInput.textContainerInset.top + self.textInput.textContainerInset.bottom);
}

// 添加通知
-(void)addEventListening
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}

/**
 初始化UI
 */
-(void)setupSubviews {
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, 0.5)];
    line.backgroundColor = RGBACOLOR(227, 228, 232, 1);
    [self addSubview:line];
    
    self.sendBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.width - kButtonW - 10, (self.height - kButtonH)/2.0, kButtonW, kButtonH)];
    [self.sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    self.sendBtn.layer.cornerRadius = kButtonH/2.0;
    self.sendBtn.layer.masksToBounds = YES;
    [self.sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.sendBtn.titleLabel.font = [UIFont systemFontOfSize:15.f];
    
//    [self.sendBtn setBackgroundImage:[UIImage imageNamed:@"c收藏后"] forState:UIControlStateNormal];
    [self.sendBtn setBackgroundColor:[UIColor orangeColor]];
   
    [self.sendBtn addTarget:self action:@selector(didClickSendBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.sendBtn];

    self.textInputBackView = [[UIView alloc] init];
    self.textInputBackView.backgroundColor = [UIColor whiteColor];
     self.textInputBackView.layer.cornerRadius = kInputHeight/2.0;
    self.textInputBackView.layer.borderColor = RGBACOLOR(227, 228, 232, 1).CGColor;
    self.textInputBackView.layer.borderWidth = 1;
    self.textInputBackView.layer.masksToBounds = YES;
    [self addSubview:self.textInputBackView];
    [self.textInputBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(10);
        make.centerY.equalTo(self);
        make.right.equalTo(self.sendBtn.mas_left).offset(-15);
        make.height.equalTo(@(kInputHeight));
    }];
    
    self.textInput = [[UITextView alloc] init];
    self.textInput.font = [UIFont systemFontOfSize:15];

    self.textInput.returnKeyType = UIReturnKeySend;
    self.textInput.enablesReturnKeyAutomatically = YES;
    self.textInput.delegate = self;
    self.textInput.showsVerticalScrollIndicator = NO;
    self.textInput.showsHorizontalScrollIndicator = NO;
    [self.textInputBackView addSubview:self.textInput];
    [self.textInput mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.textInputBackView).offset(12);
        make.right.equalTo(self.textInputBackView).offset(-12);
        make.top.bottom.equalTo(self.textInputBackView);
    }];
    
    
    self.placeholderLabel = [[UILabel alloc]init];
    self.placeholderLabel.textColor = [UIColor lightGrayColor];
    self.placeholderLabel.font = self.textInput.font;
    if (!self.placeholderLabel.text.length) {
        self.placeholderLabel.text = @" ";
    }
    [self addSubview:self.placeholderLabel];
    [self.placeholderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.textInput).offset(3);
        make.centerY.equalTo(self.textInput);
    }];
   
    
    
}
#pragma mark keyboardnotification
- (void)keyboardWillShow:(NSNotification *)notification
{
    
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    _keyboardHeight = keyboardFrame.size.height;
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:7];
    NSLog(@"%f==%f=====%f",keyboardFrame.origin.y,self.height,_origin_y);
    
    self.y = (keyboardFrame.origin.y - self.height);
    [UIView commitAnimations];
    
    
    self.keyboardIsVisiable = YES;
    if (self.keyIsVisiableBlock) {
        self.keyIsVisiableBlock(YES);
    }
}

- (void)keyboardWillHidden:(NSNotification *)notification
{
    
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        
        if (self.textInput.text.length == 0) {
            self.y = self.origin_y;
            
        }else{
            self.y = self.currentPut_Y;
        }
        if ([_delegate respondsToSelector:@selector(putViewHeight:)]) {
            [_delegate putViewHeight:self.height];
        }
    }];
    self.keyboardIsVisiable = NO;
    if (self.keyIsVisiableBlock) {
        self.keyIsVisiableBlock(NO);
    }
}
#pragma mark UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    if(![textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length) {
        NSLog(@"输入为空");
        textView.text =[textView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        self.placeholderLabel.hidden = NO;
        
        [self.sendBtn setBackgroundImage:[UIImage imageNamed:@"c收藏后"] forState:UIControlStateNormal];
    }else{
         self.placeholderLabel.hidden = YES;
        
        [self.sendBtn setBackgroundImage:[UIImage imageNamed:@"SV_gift_sendBG"] forState:UIControlStateNormal];
    }
   
    
    _textInputHeight = ceilf([self.textInput sizeThatFits:CGSizeMake(self.textInput.width, MAXFLOAT)].height);
    self.textInput.scrollEnabled = _textInputHeight > _textInputMaxHeight && _textInputMaxHeight > 0;
    if (self.textInput.scrollEnabled) {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:7];
        self.textInput.height = 5 + _textInputMaxHeight;
        self.y = SCREEN_HEIGHT - _keyboardHeight - _textInputMaxHeight - _chazhi;
        self.height = _textInputMaxHeight + _chazhi;

        
        [UIView commitAnimations];
        self.currentPut_Y = SCREEN_HEIGHT - _textInputMaxHeight - _chazhi;
    } else {
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:7];
        
        [self.textInputBackView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@(_textInputHeight));
        }];

        self.y = SCREEN_HEIGHT - _keyboardHeight - _textInputHeight - _chazhi;
        self.height = _textInputHeight + _chazhi;
        self.sendBtn.y = (self.height - kButtonH)/2;

        
        [UIView commitAnimations];
        self.currentPut_Y = SCREEN_HEIGHT - _textInputHeight - _chazhi;
        
      
    }
    
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    // 点击return按钮
    if ([text isEqualToString:@"\n"]){
        if (self.textInput.text.length != 0) {
            if ([_delegate respondsToSelector:@selector(inputToolbar:sendContent:)]) {
                [_delegate inputToolbar:self sendContent:self.textInput.text];
            }
        }
        
        return NO;
    }
    return YES;
}

// 发送
-(void)didClickSendBtn:(UIButton *)sender{
    if (self.textInput.text.length != 0) {
        if ([_delegate respondsToSelector:@selector(inputToolbar:sendContent:)]) {
            [_delegate inputToolbar:self sendContent:self.textInput.text];
        }
    }

}

// 发送成功 清空文字 更新输入框大小
-(void)sendSuccessEndEditing {
    self.textInput.text = nil;
//    [self.textInput.delegate textViewDidChange:self.textInput];
    [self endEditing:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
